var listOrder = new Array;	

function createQuestionsOrder(selectedCatagory) {
	$('form.difficulty input').each(function(index) {
		if ($(this).attr("checked") == "checked") {
			difficultyLevel = index;
		}
	});

	var listLength = questionArray.length;
	var questionsInThisCatagory = [];
	for (i = 0; i < listLength; i ++) { 
		for (o = 0; o < questionArray[i].catagories.length; o++) {
			if (questionArray[i].catagories[o] == selectedCatagory && (questionArray[i].difficulty == difficultyLevel || difficultyLevel == 0)) {
				questionsInThisCatagory.push(i);
			}
		}
		listOrder[i] = i;
		};
	//alert(questionsInThisCatagory.length);
	//shuffle(listOrder);
	shuffle(questionsInThisCatagory);
}	
	
//shuffles list in-place
function shuffle(list) {
  var i, j, t;
  for (i = 1; i < list.length; i++) {
    j = Math.floor(Math.random()*(1+i));  // choose j in [0..i]
    if (j != i) {
      t = list[i];                        // swap list[i] and list[j]
      list[i] = list[j];
      list[j] = t;
    }
  }
  //listOrder = list;
  questionsInThisCatagory = list;
}	

// jQuery Shuffler from CSSTricks http://css-tricks.com/snippets/jquery/shuffle-dom-elements/
(function($){
     $.fn.shuffle = function() {
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
         this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
         return $(shuffled);
     };
 })(jQuery);

function compileQuestion(questionNumber){
	var thisQuestion = "";
	thisQuestion = thisQuestion + "<h2>" + questionArray[questionNumber].question + "</h2><div id='result'></div>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum1' >" + questionArray[questionNumber].answer1 + "</a>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum2' >" + questionArray[questionNumber].answer2 + "</a>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum3' >" + questionArray[questionNumber].answer3 + "</a>";
	return thisQuestion;
}

function testQuestionLength(thisQuestion) {
	var newFontSize = '100%';
	if (thisQuestion.length <= 10) {
		newFontSize = '120%';
	} else if (thisQuestion.length > 30 && thisQuestion.length < 100) {
		newFontSize = '200%';
	} else {
		newFontSize = '50%';
	};
	return newFontSize;
}

function generateQuestion(questionNumber) {
	buttonAlreadyPressed = false;
	var thisQuestion = compileQuestion(questionNumber);
	$("content").fadeIn();
	$("#current-question").append(thisQuestion);
	$('a').shuffle();
	$("content").trigger('create');
	
	/*var qlen1 = testQuestionLength(questionArray[questionNumber].answer1);
	$('.qnum1 span').css('font-size','10px');
	var qlen2 = testQuestionLength(questionArray[questionNumber].answer2);
	$('.qnum2 span').css('font-size','20px');
	var qlen3 = testQuestionLength(questionArray[questionNumber].answer3);
	$('.qnum3 span').css('font-size','30px');*/
	
	$(".answer-button").click(function() { 
		if (buttonAlreadyPressed == false) {
			if ( $(this).hasClass('qnum1') ) {selectedAnswerNumber = 1; selectedClass = 'qnum1';};
			if ( $(this).hasClass('qnum2') ) {selectedAnswerNumber = 2; selectedClass = 'qnum2';};
			if ( $(this).hasClass('qnum3') ) {selectedAnswerNumber = 3; selectedClass = 'qnum3';};
			checkAnswer(questionNumber, selectedAnswerNumber, selectedClass, parseInt(green)); 
			buttonAlreadyPressed = true;
		} else {
			return false;
		};

	});
	
	$("div#timer-container").css("display","block");
	var count=15;
	var red = 0;
	var green = 100;
	var spanColor = "rgb(" + red +"%," + green + "%,0%)";
	var counter=setInterval(timer, 100);

	function timer() {
		var newWidth = (count*10)/1.5;
		red = red + 0.6;
		green = green - 0.6;
		spanColor = "rgb(" + red +"%," + green + "%,0%)";
		newWidth = newWidth + "%";
		$("div#timer").empty().css("width",newWidth).css("background-color", spanColor);
		count = count - 0.1;
		if (count <= 0) {
			clearInterval(counter);
			outOfTime(questionNumber);
			return;
		}
		if (selectedAnswerNumber) {
			clearInterval(counter);
			return;
		} 
	}

}
	
function checkAnswer(thisQuestionNumber, selectedAnswerNumber, selectedClass, green) {

	/*
	var attrs = { };
	$.each($("a.answer-button")[0].attributes, function(idx, attr) {
		attrs[attr.nodeName] = attr.nodeValue;
	});
	$("a.answer-button").replaceWith(function () {
		return $("<p />", attrs).append($(this).contents());
	});*/
	
	$("span.ui-btn-inner").css({'background-color': '#ffaaaa'});
	if (selectedAnswerNumber == questionArray[thisQuestionNumber].correctAnswer) {
		$("a." + selectedClass).buttonMarkup({ icon: "check" });
		$("a." + selectedClass + " span.ui-btn-inner").css({'background-color': '#aaffaa'});
		$("#result").append("<p>Correct Answer!</p>").css({"color": "#009900"});
		score = score + green;
		$("#score-total").empty().append(score);
	} else { 
		$("a." + selectedClass).buttonMarkup({ icon: "delete" });
		$("a.qnum" + questionArray[thisQuestionNumber].correctAnswer + " span.ui-btn-inner").css({'background-color': '#aaffaa'});
		$("#result").append("<p>Wrong Answer!</p>").css({"color": "#cc0000"});
	};
	
	$("#next-button-container").append("<a href='#' data-role='button' data-icon='arrow-r' data-mini='true' class='next-button' style='margin-top:20px;' >NEXT</a>");
	$("#next-button-container").fadeIn('slow', function() {});
	$("content").trigger('create');
	$(".next-button").click(function() {
		clearQuestion();
		questionTotal ++;
		$("#question-number").empty().append(questionTotal + 1 + "/" + gameLength);
	});
};

function outOfTime(thisQuestionNumber) {
	$("span.ui-btn-inner").css({'background-color': '#ffaaaa'});
	$("a.qnum" + questionArray[thisQuestionNumber].correctAnswer + " span.ui-btn-inner").css({'background-color': '#aaccff'});
	$("div#timer").empty().css("width","100%").append("<p>Out of time!</p>").css({"color": "#cc0000"}).css({"background-color": "#ffffff"});
	$("#next-button-container").empty().append("<a href='#' data-role='button' data-icon='arrow-r' data-mini='true' class='next-button' style='margin-top:20px;' >NEXT</a>");
	$("#next-button-container").fadeIn('slow', function() {});
	$("content").trigger('create');
	$(".next-button").click(function() {
		clearQuestion();
		questionTotal ++;
		$("#question-number").empty().append(questionTotal + 1 + "/" + gameLength);
	});
}

function clearQuestion() {
	selectedAnswerNumber = null;
	$("content").fadeOut('fast', function() {
		$("#current-question").empty()
		$(".next-button").remove();
		$("#next-button-container").fadeOut();
		currentQuestionNumber = questionsInThisCatagory[questionTotal];
		if (questionTotal == gameLength) { 
				endGame(); 
			} else {
				generateQuestion(currentQuestionNumber, selectedCatagory); 
			};
	});
}

function showQuestionNumber() {
	$("#question-number").append(questionTotal + 1 + "/" + gameLength);
	$("#score-total").append(score);
}

function generateCatagoryList() {
	var catsMessage = "Pick a catagory:";
	catsMessage = "<ul data-role='listview' data-inset='true'><li><a href='#'>General</a></li><li><a href='#'>Stories</a></li><li><a href='#'>Characters</a></li><li><a href='#'>Locations</a></li><li><a href='#'>Quotes</a></li><li><a href='#'>M.R. James's Life</a></li></ul>";
	$("content").fadeIn();
	$("#current-question").append(catsMessage);
	$("content").trigger('create');
	$("content a").each(function(index) {
		$("content a").eq(index).click(function() {
			selectedCatagory = index;
			$("content").fadeOut('fast', function() {
				clearQuestion();
				createQuestionsOrder(selectedCatagory);
				generateQuestion(listOrder[questionTotal]);
			});
		});
	});
}

function showStartScreen() {
	var startMessage = "";
	startMessage = startMessage + "<div style='text-align:center'><img src='images/Website-logo-quiz-version.gif' alt='A Podcast to the Curious Logo' /></div>";
	startMessage = startMessage + "<h1>M.R. James Trivia Quiz</h1><h2 class='titlepage'>Test your ghost story knowledge!</h2>";
	startMessage = startMessage + "<p><a href='#' data-role='button' data-icon='arrow-r' data-iconpos='right' class='start-button' style='margin-top:20px;' >START</a></p>";
	/*startMessage = startMessage + "<p><a href='#' data-role='button' data-icon='arrow-r' data-iconpos='right' class='cats-button' style='margin-top:20px;' >CATAGORIES</a></p>"; */
	startMessage = startMessage + "<form class='difficulty'><fieldset data-role='controlgroup' data-mini='true'><legend>Difficulty:</legend><input name='radio-choice-v-6' id='radio-choice-v-6d' value='on' checked='checked' type='radio'><label for='radio-choice-v-6d'>All questions</label><input name='radio-choice-v-6' id='radio-choice-v-6a' value='off' type='radio'><label for='radio-choice-v-6a'>Easy</label><input name='radio-choice-v-6' id='radio-choice-v-6b' value='off' type='radio'><label for='radio-choice-v-6b'>Medium</label><input name='radio-choice-v-6' id='radio-choice-v-6c' value='other' type='radio'><label for='radio-choice-v-6c'>Hard</label></fieldset></form>";
	$("#current-question").append(startMessage);
	$("content").trigger('create');
	$(".start-button").click(function() {
		$("content").fadeOut('fast', function() {
			createQuestionsOrder(selectedCatagory);
			clearQuestion();
			generateQuestion(questionsInThisCatagory[questionTotal]);
		});
	});
	$(".cats-button").click(function() {
		$("content").fadeOut('fast', function() {
			$("#current-question").empty()
			$(".next-button").remove();
			$("#next-button-container").fadeOut();
			generateCatagoryList();
		});
	});
}

function socialMediaScore(userScore, outOf) {
	var socialMedia = '<div id="tweet-this"><a href="https://twitter.com/intent/tweet?button_hashtag=MRJamesQuiz&text=I%20scored%20' + userScore + '%20on%20the%20M.R.%20James%20Quiz!" class="twitter-hashtag-button button-left" data-size="large" data-url="http://mrjp.me/quiz" data-dnt="true">Tweet Your Score!</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';

	function fbs_click() {
			u=document.URL;
			t="I scored at monty's quiz!";
			window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
			return false;
		}
	socialMedia = socialMedia + '<a class="twitter-hashtag-button button-right" href="http://www.facebook.com/share.php?u=http://montysquiz.com" onclick="return fbs_click()" target="_blank">Share on Facebook</a>';

	return socialMedia;
}

function sendHighScore(){
	// Get the players name and validate it;
	var thePlayerName = $("#name").val();
	thePlayerName = thePlayerName.replace( /[^a-zA-Z0-9]/ , "");
		
	// Create data to send
	var datastring = 'playername=' + thePlayerName + '&playerscore=' + score + '&playerdifficulty=' + difficultyLevel + '&playerxoutofx=' + questionTotal + '&outof=' + gameLength;

	// Send data to server
	$.ajax({
		type:"POST",
		url:"http://www.willross.co.uk/quiz/data_submit.php",
		data: datastring,
		complete: function() {
			$(".popup").remove();
			$(".submit-score").remove();
			$("#current-question").append("<p class='scoreadded'>SCORE ADDED!</p>");
			$('div#highscores').empty();
			var theDiffURL = 'data_get' + difficultyLevel + '.php';
			$('div#highscores').load(theDiffURL);
		}
	});
}

function submitHighScore() {
	var scoresMessage = "<form id='sendScore' method='post' action='http://www.willross.co.uk/quiz/data_submit.php'><label for='name'>Enter your name!</label><input type='text' name='playername' id='name' data-mini='true' /><input type='hidden' name='playerscore' value='"+ score +"' /><input type='hidden' name='playerdifficulty' value='"+ difficultyLevel +"' /><input type='hidden' name='playerxoutofx' value='"+ questionTotal +"' /><input type='button' value='submit' id='scoresubmit' /></form>";
	popUp(scoresMessage);
	$("content").trigger('create');
	$("#scoresubmit").click(function(){
		sendHighScore();
	});
	$("#sendScore").submit(function(){
		sendHighScore();
		return false;
	});
}

function generateHighScoreTable() {
	
	$('div#highscores').empty();
	var theDiffURL = 'data_get' + difficultyLevel + '.php';
	$('div#highscores').load(theDiffURL);
	
}

function endGame() {
	$("div#timer-container").css("display","none");
	$("content").fadeIn();
	$("#question-number-heading").empty();
	$("#score").empty();
	var catagoryWords = ['general','Which story','Characters','Locations','Quotes','Monty\'s Life'];
	var endMessage = "<h2>Well done! " + score + " points!<br />You got " + questionTotal + " out of " + gameLength + " correct!";
	/*endMessage = endMessage + "<h3>Difficulty: " + difficulties[difficultyLevel] + ".</h3>";*/
	$("#current-question").append(endMessage);
	var socialMedia = socialMediaScore(score, questionTotal);
	$("#current-question").append(socialMedia);
	$("#current-question").after("<div id='highscores'></div><a href='#' data-role='button' data-icon='refresh' class='restart-button' style='margin-top:30px;' >RESTART</a>");
	generateHighScoreTable();
	$("#highscores").after("<a href='#' data-role='button' data-icon='refresh' class='submit-score' style='margin-top:30px;' >Submit score</a>");
	$("content").trigger('create');
	$(".restart-button").click(function() {
		location.reload();
	});
	$(".submit-score").click(function() {
		submitHighScore();
	});
}

// These 3 lines prevent the url bar from appearing on load with
// mobile and when the user changes from portrait to landscape.
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
window.addEventListener("orientationchange", function() { hideURLbar();});
function hideURLbar(){
   window.scrollTo(0,1);
}

function popUp(message) {
	$("content").prepend("<div class='popup'><p>" + message + "</p></div>");
}

// Set up global variables for game
var currentQuestionNumber = 0;
var questionTotal = 0;
var score = 0;
var selectedAnswerNumber = 0;
var selectedCatagory = 0;
var gameLength = 5;
var difficultyLevel = 0;
var difficulties = ['Easy, Medium and Hard', 'Easy', 'Medium', 'Hard'];
var buttonAlreadyPressed = false;

// Once page has loaded, start the game.
$(function() {
	//alert(questionArray.length);

	$("#next-button-container").fadeOut();
	//alert(questionArray[2].catagories[1]);
	//createQuestionsOrder();
	showStartScreen();
	//generateQuestion(listOrder[questionTotal]);
	showQuestionNumber();
	//popUp("Hello");
});